package com.aitaoxue.palx.service;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.api.ApiHttpClient;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AlarmReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		Log.d("AlarmReceiver", "begin login");
		AitaoXueApi
				.login(AppContext.getInstance().getProperty("user.username"),
						AppContext.getInstance().getProperty("user.password"),
						mHandler);
	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			ApiHttpClient.clearUserCookies(AppContext.getInstance());
			AsyncHttpClient client = ApiHttpClient.getHttpClient();
			HttpContext httpContext = client.getHttpContext();
			CookieStore cookies = (CookieStore) httpContext
					.getAttribute(ClientContext.COOKIE_STORE);
			if (cookies != null) {
				String tmpcookies = "";
				for (Cookie c : cookies.getCookies()) {
					tmpcookies += (c.getName() + "=" + c.getValue()) + ";";
				}
				ApiHttpClient.setCookie(tmpcookies);
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}
	};

}
